var omnibox_supermark = {};

// 获取内容
chrome.storage.sync.get({
	WZY_NEW_TAB_VALUE: "null",
}, function(items) {
	var value = items.WZY_NEW_TAB_VALUE;

	if(value == "null"){
		value=new Array();
	}
	omnibox_supermark =value;		
});	

// changed handler to keep notice of option change
chrome.storage.onChanged.addListener(function (changes, namespace) {
  if (namespace === 'sync') {
    for (var key in changes) {
      if (key == 'WZY_NEW_TAB_VALUE') {
        omnibox_supermark = changes[key].newValue
      }
    }
  }
})
	
chrome.omnibox.onInputStarted.addListener(function(){});

//chrome.omnibox.setDefaultSuggestion({'description': 'yes'})

chrome.omnibox.onInputChanged.addListener(
  function(text, suggest)
  {
	 if(text.length == 0){
		return;
	 }
	 
	 var list = [];
	 for(var i in omnibox_supermark.list)
	 {
		var Title = "" + omnibox_supermark.list[i].Key;
		Title = Title.toUpperCase();
		if(Title.indexOf(text.toUpperCase()) >= 0)
		{			
			list.push({
			  'content': omnibox_supermark.list[i].URL,
			  'description':'<url>'+omnibox_supermark.list[i].URL+'</url> <dim>'+' key: </dim> <match>'+omnibox_supermark.list[i].Key+'</match> - <dim>'+ omnibox_supermark.list[i].Title +'</dim>'
			});
		}
	}
	suggest(list);
  });

chrome.omnibox.onInputEntered.addListener(function (text, type) {
	
	var FormatUrl = "";
	
	// 必须加上http 的前缀，所以没有的要加上
	if(text.indexOf("http://") != 0 && text.indexOf("https://") != 0){
		FormatUrl = "https://www.google.com/#q=" + text;		
	}
	else{
		FormatUrl = text;		
	}
	
	if (type !== 'currentTab') {
		chrome.tabs.create({url: FormatUrl, active: type === 'newForegroundTab'})
	} else {
		chrome.tabs.query({lastFocusedWindow: true, windowType: 'normal'}, function (tab) {
			chrome.tabs.update(tab.id, {url: FormatUrl}, function () {})
		})
	}
});
